package com.aaa.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class WxUtil {


    /**
     * 小程序id
     */
    private static final String appId = "wxca0b806bca891727";

    /**
     * 小程序密钥
     */
    private static final String secret = "b225a771f64e169be95cff5e0dc99541";




    /**
     * @param code
     * @return String
     * @author 胡博魁
     * @date 2023-06-15
     * @description
     *
     *
     * 获取openid
     */
    public static String getOpenid(String code) {

        try {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            String url ="https://api.weixin.qq.com/sns/jscode2session?appid="+appId+"&secret="+secret+"&js_code="+code+
                    "&grant_type=authorization_code";
            HttpGet get = new HttpGet(url);
            CloseableHttpResponse response = httpclient.execute(get);
            String result = EntityUtils.toString(response.getEntity(), "utf-8");
            JSONObject json = JSONObject.parseObject(result);
            if(!json.containsKey("errcode")) {
                return json.getString("openid");
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("openid获取失败");
        }
        return null;
    }
}
